<?
	session_start(); if (!$_SESSION['logged']) {header("Location: index.php"); die();}

	$tovar_img_dir = "/user/tovar/";
	$tovar_tmb_dir = "/user/images/tovar_tmb/";

	include_once ('../core/adds.php');

	function check_cat_dis($cat_name,$disabled_res,$show) {
		if (preg_match_all("/".$cat_name."/",file_get_contents("../user/tovar.php"),$tmp) > 0) {
			return $show?$disabled_res:'';
		}
		else
			return !$show?$disabled_res:'';
	}

//	echo "<pre>"; print_r ($_POST); echo "</pre>";
	if (!empty($_POST)) {
		$tmp_ids = explode("&",$_POST['item_id_order']);
		$item_id = array();
		foreach ($tmp_ids as $tmp_id) eval('$'.$tmp_id.';');

		$out_file = '<?'."\n";
		$i=1;
		$cur_cats = array();
		$field_kind = array('name','desc');
		foreach ($item_id as $id) {
//			echo "#$fk#".$_POST['category_'.$id.'_'.$fk]."#\n";
			if (empty($_POST['category_'.$id.'_name'])) {
				$_POST['category_'.$id.'_name'] = translit($_POST['category_'.$id.'_desc']);
			}
			foreach ($field_kind as $fk) // название и описание
				$out_file .= "\t".'$category_'.$i.'_'.$fk.' = "'
							.str_replace('"','&quot;',$_POST['category_'.$id.'_'.$fk]).'";'."\n";
			// проверяем наличие каталогов
	/*		if (!is_dir('..'.$tovar_img_dir.$_POST['category_'.$id.'_name'])) {
				mkdir('..'.$tovar_img_dir.$_POST['category_'.$id.'_name']);
				mkdir('..'.$tovar_tmb_dir.$_POST['category_'.$id.'_name']);
			}*/
			$cur_cats []= $_POST['category_'.$id.'_name'];
			$out_file .= "\n";
			$i++;
		}
		$out_file .= '?>'."\n";

//		echo "<pre>"; print_r ($out_file); echo "</pre>";

		// если есть категории на удаление - пристреливаем соответствующие пустые каталоги
	/*	$old_cats = array_splice(scandir('..'.$tovar_img_dir),2);
		$cats_2_remove = array_diff($old_cats,$cur_cats);
		if (!empty($cats_2_remove))
		foreach ($cats_2_remove as $cat_2_remove) {
			rmdir('..'.$tovar_img_dir.$cat_2_remove);
			rmdir('..'.$tovar_tmb_dir.$cat_2_remove);
		}   */

		if (file_exists('../user/category.php'))
			rename('../user/category.php','../user/backups/bak_category_'.date('YmdHis').'.php')
			or die('Не удалось создать резервную копию category.php!');
		file_put_contents('../user/category.php',$out_file);
	}

	$mnemonics = array('#CAT_ID#');
	$category_template = '	<tr id="#CAT_ID#" class="id">
		<td class="del_item_row">
			<!--input type="button" value="del" onclick="<?=check_cat_dis(${"category_#CAT_ID#_name"},"del_item(#CAT_ID#)",false)?>"<?=check_cat_dis(${"category_#CAT_ID#_name"}," disabled",true)?>-->
			<a class="<?=check_cat_dis(${"category_#CAT_ID#_name"},"disabled_",true)?>small_button" onclick="<?=check_cat_dis(${"category_#CAT_ID#_name"},"del_item(#CAT_ID#)",false)?>"><span>del</span></a>
		</td>
		<td class="dragHandle"></td>
		<td class="value">
			<table>
				<tr>
					<td>Название категории</td>
					<td>
						<input name="category_#CAT_ID#_desc" type="text" value="<?=${"category_#CAT_ID#_desc"}?>">
						<input name="category_#CAT_ID#_name" type="hidden" value="<?=${"category_#CAT_ID#_name"}?>">
					</td>
				</tr>
			</table>
		</td>
	</tr>';


?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"[]>
<html lang="ru-RU">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Редактирование категорий</title>
    <link rel="stylesheet" href="/core/reset.css" type="text/css" media="screen" />
    <link rel="stylesheet" href="/adm/adm_style.css" type="text/css" media="screen" />
    <!--[if IE 6]><link rel="stylesheet" href="/core/style.ie6.css" type="text/css" media="screen" /><![endif]-->
    <!--[if IE 7]><link rel="stylesheet" href="/core/style.ie7.css" type="text/css" media="screen" /><![endif]-->
	<script type="text/javascript" src="/core/jquery.js"></script>
	<script type="text/javascript" src="/core/jquery.tablednd_0_5.js"></script>
	<script>
		$(document).ready(function() {
			$("#item_id").tableDnD({
				dragHandle: "dragHandle"
			});

			$("#item_id tr.id").hover(function() {
				$(this.cells[1]).addClass('showDragHandle');
			}, function() {
				$(this.cells[1]).removeClass('showDragHandle');
			});
		});

		function add_item() {
			var new_id = document.getElementById('new_cat_id').value;
			document.getElementById('new_cat_id').value = new_id*1 + 1;
			var tmp = document.getElementById('item_id').getElementsByTagName('TBODY')[0].innerHTML;
			$('#item_id_body').html(tmp+'<?=preg_replace("/\<\?((?!\?\>).)*\?\>/","",str_replace(array("\r","\n"),"",$category_template))?>'.replace(/#CAT_ID#/g,new_id));
			$("#item_id").tableDnDUpdate();
			$("#item_id tr.id").hover(function() {
				$(this.cells[1]).addClass('showDragHandle');
			}, function() {
				$(this.cells[1]).removeClass('showDragHandle');
			});
		}

		function del_item(item_id) {
			if (confirm('Вы действительно хотите удалить категорию "'
				+$("input[name='category_"+item_id+"_desc']").val()+'"?')) {
					$("#"+item_id).remove()
			}
		}
	</script>
</head>

<body style="min-width:500px;">
<?php
	include ('../user/category.php');
?>
<div id="make_category">
<form name="category_form" enctype="multipart/form-data" action="make_category.php" method="post"
	onsubmit="document.getElementById('item_id_order').value = $('#item_id').tableDnDSerialize();">
<input name="item_id_order" id="item_id_order" type="hidden" value="">
<span class="cfg_section_name">Категории</span>
<a class="button" href="#" onclick="$('form[name=category_form]').submit();"><span>Сохранить</span></a><br /><br /><br />
<table class="adm_table" id="item_id"><tbody id="item_id_body">
<?
	$cat_id = 0;
	while (!empty(${"category_".++$cat_id."_desc"})) {
		$cur_template = $category_template;
		foreach ($mnemonics as $mnem) {
			$cur_template = str_replace($mnem,${strtolower(substr($mnem,1,-1))},$cur_template);
	//		echo ${strtolower(substr($mnem,1,-1))};
		}
		eval ('?>'.$cur_template.'<?');
	}
?>
</tbody>
</table>
<br />
<input id="new_cat_id" type="hidden" value="<?=$cat_id?>">
<a class="button" href="#" onclick="$('form[name=category_form]').submit();"><span>Сохранить</span></a>&nbsp;&nbsp;&nbsp;
<a class="button" href="#" onclick="add_item()"><span>Добавить</span></a>
</form>
</div>
</body>

</html>